const router = require('express').Router();
const orderService = require('../../service/order');
const joi = require('joi');
const joiValidate = require('../../utils/joiValidate');
const LockUtil = require('../../utils/lockUtil');
const ErrorCode = require('../../utils/errorCode');
const verifyUser = require('../../utils/jwtHanlder');

/**
 * @apiDefine Order  订单相关接口
 */

/**
 * @api {post} /v1/order/add  购买课程
 * @apiVersion 1.0.0
 * @apiName OrderAdd
 * @apiGroup  Order
 *
 * @apiDescription 购买课程
 *
 * @apiParam {Number} courseId  课程Id
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/order/add
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 {
    "code": 200,
    "message": "请求成功",
    "data": {
        "orderId": 36
    }
}
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.post('/add', verifyUser.verify(), joiValidate(joi.object().keys({
  courseId: joi.number().required().label('请选择需要购买的课程')
})), (req, res, next) => {
  const { courseId } = req.body;
  const { userId } = req.user;
  // todo 操作记录
  // 创建申请创建锁，避免重复提交
  const lockUtil = new LockUtil(`course:buy:${userId}:`, courseId , 120);
  return lockUtil.tryLock()
    .then(() => orderService.buy({ userId, courseId }))
    .then((data) => {
      // 删除请求锁
      lockUtil.unlock().catch(console.error);
      res.success(data);
    })
    .catch((err) => {
      // 非频繁访问时删除频繁队列key
      if (err.code !== ErrorCode.FREQUENT_REQUEST) lockUtil.unlock().catch(console.error);
      next(err);
    });
});

/**
 * @api {get} /v1/order/refund/rule 获取订单的退款规则
 * @apiVersion 1.0.0
 * @apiName OrderRefundRule
 * @apiGroup  Order
 *
 * @apiDescription 获取订单的退款规则
 *
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/order/refund/rule
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 {
    "code": 200,
    "message": "请求成功",
    "data": {
        "orderId": 36
    }
}
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.get('/refund/rule', (req, res, next) => {
  orderService.getOrderRefundRule()
    .then((data) => res.success(data))
    .catch(e => next(e))
});

module.exports = router;
